import React from 'react';
import * as AntdIcons from '@ant-design/icons';

export interface IconRendererProps {
  icon: string;
  size?: number;
  showName?: boolean;
  style?: React.CSSProperties;
  className?: string;
  fallback?: React.ReactNode;
}

const IconRenderer: React.FC<IconRendererProps> = ({
  icon,
  size = 16,
  showName = false,
  style = {},
  className = '',
  fallback = null,
}) => {
  if (!icon) {
    return fallback || <span style={{ color: '#999' }}>-</span>;
  }

  // 尝试直接匹配图标组件
  const IconComponent = (AntdIcons as any)[icon];

  if (IconComponent) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }} className={className}>
        <IconComponent style={{ fontSize: size, ...style }} />
        {showName && (
          <span style={{ fontSize: '12px', color: '#666' }}>
            {icon.replace('Outlined', '').replace('Filled', '')}
          </span>
        )}
      </div>
    );
  }

  // 如果直接匹配失败，尝试其他可能的图标名称格式
  const possibleIconNames = [
    icon,
    `${icon}Outlined`,
    `${icon}Filled`,
    icon.charAt(0).toUpperCase() + icon.slice(1),
    `${icon.charAt(0).toUpperCase() + icon.slice(1)}Outlined`,
    `${icon.charAt(0).toUpperCase() + icon.slice(1)}Filled`,
  ];

  for (const iconName of possibleIconNames) {
    const PossibleIcon = (AntdIcons as any)[iconName];
    if (PossibleIcon) {
      return (
        <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }} className={className}>
          <PossibleIcon style={{ fontSize: size, ...style }} />
          {showName && (
            <span style={{ fontSize: '12px', color: '#666' }}>
              {iconName.replace('Outlined', '').replace('Filled', '')}
            </span>
          )}
        </div>
      );
    }
  }

  // 如果所有尝试都失败，显示备用内容
  return fallback || (
    <span style={{ fontSize: '12px', color: '#999', ...style }} className={className}>
      {icon}
    </span>
  );
};

export default IconRenderer;